import { useRoute } from 'vue-router'
import { CustomComDesign } from './utils/index'
import { ref, unref, computed, markRaw, onMounted, watch } from 'vue'
import {
  getCortomComList,
  getComDesignInfo,
  useComDesignStoreWithOut,
} from '@/store'

import type { DefineComponent } from 'vue'
import {
  BwCustomComFrontTypeEnum,
  type BwCustomComDesignInfoModel,
} from '@bitwit/base-com-render'

export function useCreate() {
  const route = useRoute()
  const designStore = useComDesignStoreWithOut()

  const desiginCreate = ref()
  const myEle = ref<any | DefineComponent>(null)
  const curDesignInfo = ref<BwCustomComDesignInfoModel | null>(null)

  const curDesign = new CustomComDesign({
    front: BwCustomComFrontTypeEnum.pc,
  })

  const isPcFront = computed(() => {
    const type = designStore.curFrontType
    return BwCustomComFrontTypeEnum.pc === type
  })

  /** 获取设计看板容器 */
  const getContainer = () => unref(desiginCreate)

  /** 初始化设计器画布 */
  const initDesign = (formInfo: BwCustomComDesignInfoModel) => {
    try {
      curDesign.setDesignInfo(formInfo)

      const ele: any = curDesign.getCom()
      myEle.value = markRaw(ele)
    } catch (error) {
      console.error(error)
    }
  }

  onMounted(() => {
    const { appId, pageId } = route.params
    const curAppId = appId ? appId.toString() : ''
    const curPageId = pageId ? pageId.toString() : ''

    Promise.all([
      getCortomComList(undefined, ['系统基础组件', '组件属性配置组件']),
      getComDesignInfo(curAppId, curPageId),
    ]).then(([comList]) => {
      const designInfo = designStore.getDesignInfo
      console.log('designInfo', designInfo)
      designStore.setCustomComList(comList)
      curDesignInfo.value = designInfo
      designInfo && initDesign(designInfo)
    })
  })

  /** 初始化选中状态 */
  const setSeleNodeState = (nodeId?: Nullable<string>) => {
    const time = setTimeout(() => {
      clearTimeout(time)
      curDesign.onSelectNode(nodeId ?? '')
    }, 100)
  }

  watch(
    () => designStore.selectNodeEle,
    (newVal) => {
      setSeleNodeState(newVal?.nodeId)
    },
    { deep: true, immediate: true }
  )

  watch(
    () => designStore.curHideNodeIds,
    (newVal) => {
      const time = setTimeout(() => {
        clearTimeout(time)
        curDesign.onHideNodeEle(newVal ?? [])
      }, 100)
    },
    { deep: true, immediate: true }
  )

  watch(
    () => designStore.curFrontType,
    (newVal) => {
      const designInfo = designStore.getDesignInfo
      if (designInfo) {
        curDesign.setFrontType(newVal)

        curDesignInfo.value = designInfo
        designInfo && initDesign(designInfo)
      }
    },
    { deep: true, immediate: false }
  )

  return { myEle, isPcFront, desiginCreate, getContainer }
}
